package com.okilo.online.app.tools.extensions

import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import org.json.JSONArray
import org.json.JSONObject

// 字符串资源扩展
fun Context.getStringRes(@StringRes resId: Int): String = getString(resId)

fun Context.getStringRes(@StringRes resId: Int, vararg formatArgs: Any): String =
    getString(resId, *formatArgs)

fun Context.getStringSafe(@StringRes resId: Int, default: String = ""): String =
    try { getString(resId) } catch (e: Exception) { default }

// 颜色资源扩展
fun Context.getColorRes(@ColorRes resId: Int): Int = ContextCompat.getColor(this, resId)

fun Context.getColorSafe(@ColorRes resId: Int, default: Int): Int =
    try { ContextCompat.getColor(this, resId) } catch (e: Exception) { default }

// Drawable资源扩展
fun Context.getDrawableRes(@DrawableRes resId: Int): Drawable? =
    ContextCompat.getDrawable(this, resId)

fun Context.getDrawableSafe(@DrawableRes resId: Int, default: Drawable? = null): Drawable? =
    try { ContextCompat.getDrawable(this, resId) } catch (e: Exception) { default }

fun Context.requireDrawable(@DrawableRes resId: Int): Drawable =
    ContextCompat.getDrawable(this, resId) ?: throw Resources.NotFoundException("Drawable not found")

//金额格式化，例：1,000,000
fun String.addCommasFromEndRegex(): String {
    return this.reversed()
        .chunked(3)
        .joinToString(",")
        .reversed()
}

// JSONArray 转 List<JSONObject> 扩展函数
fun JSONArray.toListWithModification(modifier: (JSONObject) -> Unit): List<JSONObject> {
    return List(length()) { index ->
        optJSONObject(index)?.apply(modifier)
    }.filterNotNull()
}

fun JSONArray.toJSONObjectList(): List<JSONObject> {
    return List(length()) { index -> optJSONObject(index) }
}